package io.renren.config;

import java.io.IOException;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class SchedulerConfig {
	
	@Autowired
	private Environment env;
	
	
	@Bean(name = "SchedulerFactoryBean")
	public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
		SchedulerFactoryBean factory = new SchedulerFactoryBean();
		Properties pro = quartzProperties();
		
		factory.setQuartzProperties(pro);
		
		factory.setApplicationContextSchedulerContextKey("applicationContext");
		
		return factory;
	}
	
	private Properties quartzProperties() throws IOException {
		PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
		propertiesFactoryBean.setLocation(new ClassPathResource("/quartz.properties"));
		propertiesFactoryBean.setLocalOverride(true);
		Properties pro = new Properties();
		
		pro.setProperty("org.quartz.dataSource.qzDS.URL", env.getProperty("spring.datasource.druid.url"));
		pro.setProperty("org.quartz.dataSource.qzDS.user", env.getProperty("spring.datasource.druid.username"));
		pro.setProperty("org.quartz.dataSource.qzDS.password", env.getProperty("spring.datasource.druid.password"));
		pro.setProperty("org.quartz.dataSource.qzDS.driver", env.getProperty("spring.datasource.druid.driver-class-name"));
		
		//System.getProperties().putAll(pro);
		propertiesFactoryBean.setProperties(pro);
		
		//在quartz.properties中的属性被读取并注入侯在初始化对象
		propertiesFactoryBean.afterPropertiesSet();
		
		return propertiesFactoryBean.getObject();
	}
}
